import { createRouter, createWebHistory } from 'vue-router';
import Cookies from 'js-cookie';
import { useStore } from '@/store';
import { getLoginUser } from '@/api/user';

let Layout = () => import('@/layout');

const routes = [
    {
        path: '/',
        component: Layout,
        name: 'home',
        meta: { title: '首页', icon: 'house' },
        redirect: '/tender-order',
        children: [

            { path: '/tender-order', component: () => import('@/pages/tenderOrder'), meta: { title: '订单列表', 'icon': ['fa', 'user-large'] } },
            { path: '/user', component: () => import('@/pages/user'), meta: { title: '个人中心', 'icon': ['fa', 'user-large'] } },
        ]
    },
    { path: '/login', component: () => import('@/pages/login'), meta: { title: '登录' } },
    { path: '/tender-purchase', component: () => import('@/pages/tenderPurchase'), meta: { title: '购买标书' } },
    { path: '/download-tender', component: () => import('@/pages/downloadTender'), meta: { title: '下载标书' } },
    { path: '/download-tender/print', component: () => import('@/pages/downloadTender/print'), meta: { title: '打印中标' } },
    { path: '/:pathMatch(.*)*', component: () => import('@/components/404'), meta: { title: '404' } }
]
const router = createRouter({
    history: createWebHistory('/'),
    routes,
});

// 获取用户信息
let getUser = (next, to) => {
    let store = useStore();
    getLoginUser().then(res => {
        store.user = res.data;
        if (to.path == '/') next('');
        else next(to);
    })
}

// 白名单
let whiteList = ['/login', '/tender-purchase','/download-tender','/download-tender/print'];
// 全局前置守卫
router.beforeEach((to, from, next) => {
    document.title = to.meta.title ? to.meta.title + ' - 建兴招标' : '建兴招标';
    let store = useStore(),
        token = Cookies.get('token');
    // 白名单
    if (whiteList.includes(to.path)) next();
    // 有token
    else if (token) {
        if (store.user) next();
        else getUser(next, to) // 获取用户数据
    } else next('/login')
})

export default router
